package com.xiguthings.waka.web.controller.paper;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiguthings.waka.dao.DataBaseStatus;
import com.xiguthings.waka.po.Paper;
import com.xiguthings.waka.po.PaperExample;
import com.xiguthings.waka.po.extpo.Page;
import com.xiguthings.waka.publicUtils.StringUtils;
import com.xiguthings.waka.service.paper.IPaperService;
import com.xiguthings.waka.web.controller.base.AbstractController;
import com.xiguthings.waka.web.controller.base.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/paper")
@Api(tags = "试卷")
public class PaperController extends AbstractController {

    @Resource
    private IPaperService paperService;


    /**
     * 判断paperVo 如果是空的，报出异常
     *
     * @param paperVo
     */
    private void ifEmptyPaper(PaperVo paperVo, String msg) {
        if (paperVo == null || paperVo.getPaper() == null) {
            throwCodeEmptyException(msg);
        }
    }


    /**
     * 创建查询条件
     *
     * @param paperVo
     * @param example
     * @throws NumberFormatException
     */
    private void queryConditions(PaperVo paperVo, PaperExample example) throws NumberFormatException {

        PaperExample.Criteria criteria = example.createCriteria();
        // 如果查询条件为空的
        if (paperVo == null) {
            // 则查询所有未被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
            return;
        }

        // 如果有查询条件
        Paper paper = paperVo.getPaper();
        // 添加查询条件
        if (paper != null) {
            if (StringUtils.isNotBlank(paper.getPaperId())) {
                criteria.andPaperIdEqualTo(paper.getPaperId());
            }
            if (StringUtils.isNotBlank(paper.getGrowthId())) {
                criteria.andGrowthIdEqualTo(paper.getGrowthId());
            }
            if (StringUtils.isNotBlank(paper.getPaperCardId())) {
                criteria.andPaperCardIdEqualTo(paper.getPaperCardId());
            }
            if (StringUtils.isNotBlank(paper.getDescr())) {
                criteria.andDescrLike(("%" + paper.getDescr() + "%"));
            }
            if (paper.getRank() != null) {
                criteria.andRankEqualTo(paper.getRank());
            }

            if (StringUtils.isNotBlank(paper.getTips())) {
                criteria.andTipsLike("%" + paper.getTips() + "%");
            }


        }

        if (StringUtils.isNotBlank(paperVo.getInStatus())) {
            // 添加包含的状态
            String statuses = paperVo.getInStatus();
            String[] statusArr = statuses.split(",");
            List<Integer> statusList = new ArrayList<>();
            for (String str : statusArr) {
                statusList.add(new Integer(str));
            }
            criteria.andStatusIn(statusList);
        } else {
            // 如果状态的查询条件是空的，则查询没有被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
        }


    }

    /**
     * 修改或者添加
     *
     * @param paperVo
     * @return
     * @throws Exception
     */
    @ApiOperation(tags = {
            "1.控制台"}, value = "修改/添加", httpMethod = "POST",
            notes = "修改时，必须填写“paper.paperId”参数。<br>添加新记录时，growthId、paperCardId、rank是必填的",
            response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paper.paperId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.growthId", value = "所属的成长维度的主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.paperCardId", value = "提交试卷后，获得的卡片", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.descr", value = "描述信息", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.rank", value = "试卷的排序好，数字小的排在前面", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.status", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/save")
    @ResponseBody
    public ResponseEntity save(@ApiIgnore PaperVo paperVo) throws Exception {

        // 先判断是不是空参数
        ifEmptyPaper(paperVo, "传入了空参数");

        Paper paper = paperVo.getPaper();
        String paperId = paper.getPaperId();
        //判断是修改还是添加
        String msg = "";
        if (StringUtils.isNotBlank(paperId)) {
            // 修改
            paperService.updateByPrimaryKeySelective(paper);
            msg = "修改成功";
        } else {
            //添加
            msg = "添加成功";
            paperService.insert(paper);
        }

        return ajaxReturnMap(CODE_SUCCESS, msg, paper.getPaperId());
    }

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "根据主键获取记录详情", httpMethod = "GET", notes = "paperId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paper.paperId", value = "主键id", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseEntity detail(@ApiIgnore PaperVo paperVo) throws Exception {
        // 先判断是不是空参数
        String errorMsg = "paperId为空，无法查找";
        ifEmptyPaper(paperVo, errorMsg);
        Paper paper = paperVo.getPaper();
        String paperId = paper.getPaperId();
        if (StringUtils.isBlank(paperId)) {
            throwCodeEmptyException(errorMsg);
        }

        // 查询数据库
        Paper paperDB = paperService.selectByPrimaryKey(paperId);


        return ajaxReturnMap(CODE_SUCCESS,null,paperDB);
    }

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "根据主键获取记录详情", httpMethod = "GET", notes = "paperId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paper.paperId", value = "主键id,如果是过个id，请用英文逗号分隔", dataType = "String", required = true, paramType = "query")})
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity delete(@ApiIgnore PaperVo paperVo) throws Exception {
        String msg = "paperId为空，无法删除";
        ifEmptyPaper(paperVo,msg);
        Paper paper = paperVo.getPaper();
        String paperId = paper.getPaperId();
        if(StringUtils.isBlank(paperId)){
            throwCodeEmptyException(msg);
        }

        // 删除
        int row = paperService.deleteByPrimaryKey(paperId);
        if(row == 1){
            return ajaxReturnMap(CODE_SUCCESS,"删除成功",null);
        }else {
            return ajaxReturnMap(CODE_SUCCESS,"这条数据已经被删除了",null);
        }


    }

    /**
     * 分页查询
     *
     * @param paperVo
     * @param page
     * @return
     * @throws Exception
     */

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "分页查询", httpMethod = "GET", notes = "可根据条件进行筛选", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paper.paperId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.growthId", value = "所属的成长维度的主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.paperCardId", value = "提交试卷后，获得的卡片", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.descr", value = "描述信息", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paper.rank", value = "试卷的排序好，数字小的排在前面", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "inStatus", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码，如果没有值，则使用默认值。开始值从 1 开始计算", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "rows", value = "每页的数量,如果没有值，则使用默认值", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/pagelist")
    @ResponseBody
    public ResponseEntity pageList(@ApiIgnore PaperVo paperVo, @ApiIgnore Page page) throws Exception {
        PaperExample example = new PaperExample();
        // 创建查询条件
        queryConditions(paperVo,example);
        super.selectByPage(page,example,paperService);
        return ajaxReturnMap(CODE_SUCCESS,null,page);
    }

}
